import http from "./http/index.js"

// const host_o="http://192.168.2.224:8080/mall/"
const host_o="https://youpinhui.doyunet.com/mall/"
const host=host_o+"app"
const appid="wx688040d2996e474b"

const userCheckAndInit = function(callback){
	wxlogin(callback);
    uni.getStorage({
      key: 'openid',
      success: function (res) {
        if (!res.data) {
			wxlogin(callback);
        }
      },
      fail: function () {
        console.log("userCheckAndInit fail");
        wxlogin(callback);
      }
    });
}
const wxlogin = function(callback){
	uni.login({
	  provider: 'weixin',
	  success: function (res) {
		if (res.errMsg == 'login:ok') {
			http.req({code: res.code},"/wx/"+appid+"/openid").then((res)=>{
				if(res.data.success){
					var openid = res.data.data;
					/* uni.setStorage({
						key: "openid",
						data: openid
					}) */
					console.log('wxlogin request success', res.data)
					checkUserExists(callback,openid);
				}else{
					uni.showToast({
						title:res.data.msg,
						icon:"none"
					})
				}
			})
		}
	  }
	});
	
}
const checkUserExists = function (callBack,openid) {
    
    if (openid) {
      //根据openid后台查询用户是否已注册
      //没有注册，则弹窗，用户授权，后台保存用户昵称、头像，注册。
      getUserInfoByOpenid(openid, callBack);
    }
}
const getUserInfoByOpenid = function (openid, callBack) {
	http.req({openid: openid},"/member/find/openid").then((res)=>{
		if(res.data.success){
			console.log("checkUserExists 存在",res.data)
			//存在
			uni.setStorage({
				key: "openid",
				data: openid
			})
			if (callBack) {
				callBack.success(res.data)
			}
		}else{
			//不存在注册
			if (callBack) {
              callBack.fail(openid);
            }
		}
	})
}
const registUser = function(userInfo,callback){
	http.req(userInfo,"/member/regist").then((res)=>{
		if(res.data.success){
			callback(res.data.data);
		}else{
			uni.showToast({
				title: res.data.msg,
				mask: false,
				duration: 1500,
				icon:'none'
			});
		}
	})
}

export default{
	userCheckAndInit,
	getUserInfoByOpenid,
	registUser,
	host,
	host_o
}